package com.qinggeng.project.tool.pay.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.*;
import com.alipay.api.domain.AlipayFundTransToaccountTransferModel;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.*;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.qinggeng.common.enums.ShowTypeEnum;
import com.qinggeng.common.enums.TradeStatusEnum;
import com.qinggeng.common.exception.CustomException;
import com.qinggeng.common.utils.DateUtils;
import com.qinggeng.framework.redis.RedisLock;
import com.qinggeng.project.api.security.utils.ApiUtils;
import com.qinggeng.project.system.domain.GoodsVip;
import com.qinggeng.project.system.domain.HistoryWithdraw;
import com.qinggeng.project.system.domain.UserWallet;
import com.qinggeng.project.system.service.*;
import com.qinggeng.project.tool.pay.domain.AliWithdrawModal;
import com.qinggeng.project.tool.pay.domain.PayAlipay;
import com.qinggeng.project.tool.pay.domain.PayUrl;
import com.qinggeng.project.tool.pay.domain.json.AlipayConfigJson;
import com.qinggeng.project.tool.pay.domain.vo.TradeVo;
import com.qinggeng.project.tool.pay.service.AliPayService;
import com.qinggeng.project.tool.pay.service.IPayAlipayService;
import com.qinggeng.project.tool.pay.utils.PayUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class AliPayServiceImpl implements AliPayService {
    @Autowired
    private ISysConfigService configService;

    @Autowired
    private IPayAlipayService payAlipayService;

    @Autowired
    private IOrdersService ordersService;

    @Autowired
    private IOrdersReturnService ordersReturnService;

    @Autowired
    private HistoryWithdrawService historyWithdrawService;

    @Autowired
    private IUserWalletService userWalletService;

    @Resource
    private MQSendService mqSendService;

    @Resource
    private MessagePushService messagePushService;


    @Resource
    private GoodsVipService  goodsVipService;
    /**
     * 网关
     */
    //正式服
    private final String GATEWAY_URL = "https://openapi.alipay.com/gateway.do";
    //测试服
//    private final String GATEWAY_URL = "https://openapi.alipaydev.com/gateway.do";
    /**
     * 格式
     */
    private final String FORMAT = "JSON";
    /**
     * 编码
     */
    private final String CHARSET = "utf-8";
    /**
     * 签名类型
     */
    private final String SIGN_TYPE = "RSA2";

    public static  final  String SIGN="alipays://platformapi/startapp?appId=60000157&appClearTop=false&startMultApp=YES&sign_params=";


    @Value("${cycle}")
    private  String  cycleUrl;
    @Override
    public String toPayAsWeb(TradeVo trade) throws Exception{
        String fileConfigJson = configService.selectConfigByKey("sys.pay.alipay").toString();
        AlipayConfigJson configObject = JSON.parseObject(fileConfigJson, AlipayConfigJson.class);
        AlipayClient alipayClient = new DefaultAlipayClient(this.GATEWAY_URL, configObject.getAppId(), configObject.getPrivateKey(), this.FORMAT, this.CHARSET, configObject.getPublicKey(), this.SIGN_TYPE);
        // 创建API对应的request
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        // 订单完成后返回的页面和异步通知地址
        request.setReturnUrl(configObject.getReturnUrl());
        request.setNotifyUrl(configObject.getNotifyUrl());
        // 填充订单参数
        request.setBizContent("{" +
                "    \"out_trade_no\":\""+trade.getOutTradeNo()+"\"," +
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                "    \"total_amount\":"+trade.getTotalAmount().doubleValue()+"," +
                "    \"subject\":\""+trade.getSubject()+"\"," +
                "    \"body\":\""+trade.getBody()+"\"," +
                "    \"extend_params\":{" +
                "    \"sys_service_provider_id\":\""+configObject.getMerchantId()+"\"" +
                "    }"+
                "  }");//填充业务参数

        PayAlipay payAlipay = payAlipayService.selectPayAlipayByOutTradeNo(trade.getOutTradeNo());
        if (payAlipay == null){
            payAlipay = new PayAlipay();
            payAlipay.setTradeStatus(TradeStatusEnum.等待付款.getValue());
            payAlipay.setOutTradeNo(trade.getOutTradeNo());
            payAlipay.setTotalAmount(trade.getTotalAmount().doubleValue());
            payAlipay.setSubject(trade.getSubject());
            payAlipay.setBody(trade.getBody());
            payAlipayService.insertPayAlipay(payAlipay);
        }

        // 调用SDK生成表单, 通过GET方式，口可以获取url
        return alipayClient.pageExecute(request, "GET").getBody();
    }


    @Override
    public String toPayAsApp(TradeVo trade) throws Exception {
        String fileConfigJson = configService.selectConfigByKey("sys.pay.alipay").toString();
        AlipayConfigJson configObject = JSON.parseObject(fileConfigJson, AlipayConfigJson.class);
        AlipayClient alipayClient = new DefaultAlipayClient(this.GATEWAY_URL, configObject.getAppId(), configObject.getPrivateKey(), this.FORMAT, this.CHARSET, configObject.getPublicKey(), this.SIGN_TYPE);
        // 创建API对应的request
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        // 订单完成后返回的页面和异步通知地址
        request.setNotifyUrl(configObject.getNotifyUrl());
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody(trade.getBody());
        model.setSubject(trade.getSubject());
        model.setOutTradeNo(trade.getOutTradeNo());
        model.setTimeoutExpress("30m");
        model.setTotalAmount(trade.getTotalAmount().doubleValue() + "");
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);


        PayAlipay payAlipay = payAlipayService.selectPayAlipayByOutTradeNo(trade.getOutTradeNo());
        if (payAlipay == null){
            payAlipay = new PayAlipay();
            payAlipay.setTradeStatus(TradeStatusEnum.等待付款.getValue());
            payAlipay.setOutTradeNo(trade.getOutTradeNo());
            payAlipay.setTotalAmount(trade.getTotalAmount().doubleValue());
            payAlipay.setSubject(trade.getSubject());
            payAlipay.setTradeType("APP");
            payAlipay.setGmtCreate(DateUtils.getNowDate());
            payAlipay.setBody(trade.getBody());
            payAlipayService.insertPayAlipay(payAlipay);
        }

        return alipayClient.sdkExecute(request).getBody();
    }

    @Override
    public String toCyclePayAsApp(TradeVo trade) throws Exception {
        String fileConfigJson = configService.selectConfigByKey("sys.pay.alipay").toString();
        AlipayConfigJson configObject = JSON.parseObject(fileConfigJson, AlipayConfigJson.class);
        AlipayClient alipayClient = new DefaultAlipayClient(this.GATEWAY_URL, configObject.getAppId(), configObject.getPrivateKey(), this.FORMAT, this.CHARSET, configObject.getPublicKey(), this.SIGN_TYPE);
        // 创建API对应的request
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        // 订单完成后返回的页面和异步通知地址
        request.setNotifyUrl(configObject.getNotifyUrl());
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody(trade.getBody());
        model.setSubject(trade.getSubject());
        model.setOutTradeNo(trade.getOutTradeNo());
        model.setTimeoutExpress("30m");
        model.setTotalAmount(trade.getTotalAmount().doubleValue() + "");
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);
        PayAlipay payAlipay = payAlipayService.selectPayAlipayByOutTradeNo(trade.getOutTradeNo());
        if (payAlipay == null){
            payAlipay = new PayAlipay();
            payAlipay.setTradeStatus(TradeStatusEnum.等待付款.getValue());
            payAlipay.setOutTradeNo(trade.getOutTradeNo());
            payAlipay.setTotalAmount(trade.getTotalAmount().doubleValue());
            payAlipay.setSubject(trade.getSubject());
            payAlipay.setTradeType("APP");
            payAlipay.setGmtCreate(DateUtils.getNowDate());
            payAlipay.setBody(trade.getBody());
            payAlipayService.insertPayAlipay(payAlipay);
        }

         return alipayClient.sdkExecute(request).getBody();

    }

    @Override
    public String sign(Long id) throws Exception {
        String fileConfigJson = configService.selectConfigByKey("sys.pay.alipay").toString();
        AlipayConfigJson configObject = JSON.parseObject(fileConfigJson, AlipayConfigJson.class);
        AlipayClient alipayClient = new DefaultAlipayClient(this.GATEWAY_URL, configObject.getAppId(), configObject.getPrivateKey(), this.FORMAT, this.CHARSET, configObject.getPublicKey(), this.SIGN_TYPE);
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        Long userId=ApiUtils.getUserId();
        String merchantOrderNo="merchant_order_no-"+PayUtils.getOrderCode() ;
        GoodsVip goodsVip=goodsVipService.goodsVip(id);
        if (null==goodsVip){
            throw  new CustomException("购买商品不存在");
        }
        if (goodsVip.getStatus().equals("20")){
            throw  new CustomException("购买商品已经下架");
        }
        String vipUserId="";

        if (goodsVip.getSupplierDesc().equals("普通会员")){
            vipUserId=PayUtils.getOrderCode()+"-"+0+"-"+userId;
        }else {
            vipUserId=PayUtils.getOrderCode()+"-"+1+"-"+userId;
        }
        request.setNotifyUrl(cycleUrl+"/tool/pay/notify/cycleUrl");
        String bizContent="{" +
                "\"timeout_express\":\"10m\"," +//该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d,该参数数值不接受小数点,如 1.5h，可转换为 90m。
                "\"total_amount\":\""+goodsVip.getGoodsPrice()+"\"," +//订单总金额，单位为元，精确到小数点后两位，取值范围[0.01,100000000]
                "\"product_code\":\"CYCLE_PAY_AUTH\"," + //周期扣款销售产品码固定为CYCLE_PAY_AUTH。
                "\"body\":\""+goodsVip.getGoodsName()+"\"," +//对一笔交易的具体描述信息。如果是多种商品，请将商品描述字符串累加传给body。
                "\"subject\":\"会员扣款\"," +//交易标题
                "\"out_trade_no\":\""+vipUserId+"\"," +//商户网站唯一订单号
                "\"time_expire\":\""+DateUtils.getDate()+"\"," +
                "\"goods_type\":\"0\"," +//商品主类型 :0-虚拟类商品,1-实物类商品
                "\"merchant_order_no\":\""+merchantOrderNo+"\"," +  //商户原始订单号，最大长度限制32位
                "\"agreement_sign_params\":{" +
                "\"personal_product_code\":\"CYCLE_PAY_AUTH_P\"," + //周期扣款个人签约产品码固定为CYCLE_PAY_AUTH_P
                "\"external_logon_id\":\"VIP0001\"," +
                /*
                 * 请按当前接入的方式进行填充，且输入值必须为文档中的参数取值范围。
                 */
                "\"access_params\":{" +
                "\"channel\":\"ALIPAYAPP\"" +
                "}," +
                "\"sub_merchant\":{" +
                "\"sub_merchant_name\":\"品味生活\"," +
                "\"sub_merchant_service_name\":\"品味生活会员开通\"," +
                "\"sub_merchant_service_description\":\"随时取消\"" +
                "}," +
                /*
                 * 周期管控规则参数period_rule_params，
                 * 在签约周期扣款产品（如CYCLE_PAY_AUTH_P）时必传，
                 * 在签约其他产品时无需传入。
                 * 周期扣款产品，会按照这里传入的参数提示用户，并对发起扣款的时间、金额、次数等做相应限制。
                 */
                "\"period_rule_params\":{" +
                "\"period_type\":\"DAY\"," +
                "\"period\":7," +
                "\"execute_time\":\""+DateUtils.getDate()+"\"," +
                "\"single_amount\":"+goodsVip.getGoodsPrice()+"," +//单次扣款最大金额single_amount是周期扣款产品必填，即每次发起扣款时限制的最大金额，单位为元。商户每次发起扣款都不允许大于此金额。
                "}" +
                "}" +
                "}";
        request.setBizContent(bizContent);
        AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
        return response.getBody();
    }

    @Override
    public String toPayAsScan(TradeVo trade) throws Exception {
        String fileConfigJson = configService.selectConfigByKey("sys.pay.alipay").toString();
        AlipayConfigJson configObject = JSON.parseObject(fileConfigJson, AlipayConfigJson.class);
        AlipayClient alipayClient = new DefaultAlipayClient(this.GATEWAY_URL, configObject.getAppId(), configObject.getPrivateKey(), this.FORMAT, this.CHARSET, configObject.getPublicKey(), this.SIGN_TYPE);

        // 支付宝 request
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        // 订单完成后返回的页面和异步通知地址
        request.setReturnUrl(configObject.getReturnUrl());
        request.setNotifyUrl(configObject.getNotifyUrl());

        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
        model.setBody(trade.getBody());
        model.setSubject(trade.getSubject());
        model.setOutTradeNo(trade.getOutTradeNo());
        model.setTimeoutExpress("30m");
        model.setTotalAmount(trade.getTotalAmount().doubleValue() + "");
        //商品订单号码 out_trade_no 商户订单号,64个字符以内、只能包含字母、数字、下划线；需保证在商户端不重复
        model.setOutTradeNo(trade.getOutTradeNo());
        request.setBizModel(model);

        PayAlipay payAlipay = payAlipayService.selectPayAlipayByOutTradeNo(trade.getOutTradeNo());
        if (payAlipay == null){
            payAlipay = new PayAlipay();
            payAlipay.setTradeStatus(TradeStatusEnum.等待付款.getValue());
            payAlipay.setOutTradeNo(trade.getOutTradeNo());
            payAlipay.setTotalAmount(trade.getTotalAmount().doubleValue());
            payAlipay.setSubject(trade.getSubject());
            payAlipay.setBody(trade.getBody());
            payAlipayService.insertPayAlipay(payAlipay);
        }

        return alipayClient.execute(request, "GET").getQrCode();
    }

    @Override
    public boolean rsaCheck(HttpServletRequest request) {
        // 获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<>(1);
        Map requestParams = request.getParameterMap();
        for (Object o : requestParams.keySet()) {
            String name = (String) o;
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        String fileConfigJson = configService.selectConfigByKey("sys.pay.alipay").toString();
        AlipayConfigJson configObject = JSON.parseObject(fileConfigJson, AlipayConfigJson.class);
        try {
            return AlipaySignature.rsaCheckV1(params,
                    configObject.getPublicKey(),
                    CHARSET,
                    SIGN_TYPE);
        } catch (AlipayApiException e) {
            return false;
        }
    }


    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean notifyCallback(Map<String, String[]> parameterMap) {
        RedisLock redisLock = new RedisLock(redisTemplate,"NOTIFY_ORDERS_" + parameterMap.get("out_trade_no")[0]);
        try {
            if (redisLock.lockNoRetry()) {
                PayAlipay payAlipay = payAlipayService.selectPayAlipayByOutTradeNo(parameterMap.get("out_trade_no")[0]);
                if (payAlipay.getTradeStatus().equals(TradeStatusEnum.支付成功.getValue())){
                    return true;
                }
                String orderNo=parameterMap.get("out_trade_no")[0];
                //订单业务处理
                ordersService.notifyCallback(orderNo,"alipay");
                payAlipay.setTradeNo(parameterMap.get("trade_no")[0]);
                payAlipay.setBuyerId(parameterMap.get("buyer_id")[0]);
                payAlipay.setSellerId(parameterMap.get("seller_id")[0]);
                payAlipay.setGmtPayment(DateUtils.parseDate(parameterMap.get("gmt_payment")[0]));
                payAlipay.setTradeStatus(TradeStatusEnum.支付成功.getValue());
                int size=payAlipayService.updatePayAlipay(payAlipay);
                log.info("支付回调消息");
                if (size>=1){
                    //发送限购商品购买记录消息
                    mqSendService.sendUserGoodsLimitAsynMessage(orderNo);
                    //发送自动接单异步消息
                    mqSendService.sendOrdersAutoTakeAsynMessage(orderNo);
                    //发送订单打印状态延时消息
                    mqSendService.sendPrintStatusDelayMessage(orderNo);
                    //发送自动发货延时消息
                    //mqSendService.sendOrdersAutoShipDelayMessage(orderNo);

                }
            }else{
                return false;
            }
        }catch (Exception e) {
            //log.error("支付回调异常",e);
            return false;
        } finally {
            redisLock.unlock();
        }
        return true;
    }

    @Override
    public void refund(String ordersNo, BigDecimal refundAmount) throws Exception {
        log.info("支付宝退款{}",ordersNo);
        PayAlipay payAlipay = payAlipayService.selectPayAlipayByOutTradeNo(ordersNo);
        if (payAlipay.getTradeStatus().equals(TradeStatusEnum.已退款.getValue())){
            //已退款成功的直接返回正常
            return;
        }
        if (!payAlipay.getTradeStatus().equals(TradeStatusEnum.支付成功.getValue())){
            throw new CustomException("订单状态异常无法退款:"+ordersNo);
        }
//        if (Constants.DEBUG){
//            refundAmount = new BigDecimal("0.01");
//        }
        log.info("----------支付宝退款逻辑开始------------");
        String fileConfigJson = configService.selectConfigByKey("sys.pay.alipay").toString();
        AlipayConfigJson configObject = JSON.parseObject(fileConfigJson, AlipayConfigJson.class);

        AlipayClient alipayClient = new DefaultAlipayClient(this.GATEWAY_URL, configObject.getAppId(), configObject.getPrivateKey(), this.FORMAT, this.CHARSET, configObject.getPublicKey(), this.SIGN_TYPE);
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        String tradeNo = payAlipay.getTradeNo();
        String out_request_no = RandomStringUtils.randomAlphabetic(13);
        request.setBizContent("{" +
                "\"out_trade_no\":\"" + ordersNo + "\"," +
                "\"trade_no\":\"" + tradeNo + "\"," +
                "\"refund_amount\":\"" + refundAmount + "\"," +
                "\"out_request_no\":\"" + out_request_no+ "\"," +
                "\"refund_reason\":\"正常退款\"" +
                "  }");
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        log.info("信息:"+response.getBody());
        log.info("退款逻辑结束");
        if (!response.isSuccess()){
            throw new CustomException("退款失败");
        }else{
            payAlipay.setTradeStatus(TradeStatusEnum.已退款.getValue());
            payAlipay.setGmtRefund(DateUtils.getNowDate());
            payAlipay.setRefundFee(refundAmount.doubleValue());
            payAlipay.setGmtClose(DateUtils.getNowDate());
            payAlipayService.updatePayAlipay(payAlipay);

        }
    }

    public String refund(String ordersNo,Long ordersGoodsId, BigDecimal refundAmount) throws Exception {
        log.info("支付宝退款{}",ordersGoodsId);
        PayAlipay payAlipay = payAlipayService.selectPayAlipayByOutTradeNo(ordersNo);
//        if (Constants.DEBUG){
//            refundAmount = new BigDecimal("0.01");
//        }
        log.info("----------支付宝退款逻辑开始------------");
        String fileConfigJson = configService.selectConfigByKey("sys.pay.alipay").toString();
        AlipayConfigJson configObject = JSON.parseObject(fileConfigJson, AlipayConfigJson.class);

        AlipayClient alipayClient = new DefaultAlipayClient(this.GATEWAY_URL, configObject.getAppId(), configObject.getPrivateKey(), this.FORMAT, this.CHARSET, configObject.getPublicKey(), this.SIGN_TYPE);
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        String tradeNo = payAlipay.getTradeNo();
        String out_request_no = RandomStringUtils.randomAlphabetic(13);
        request.setBizContent("{" +
                "\"out_trade_no\":\"" + ordersNo + "\"," +
                "\"trade_no\":\"" + tradeNo + "\"," +
                "\"refund_amount\":\"" + refundAmount + "\"," +
                "\"out_request_no\":\"" + out_request_no+ "\"," +
                "\"refund_reason\":\"正常退款\"" +
                "  }");
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        log.info("信息:"+response.getBody());
        log.info("退款逻辑结束");
        if (!response.isSuccess()){
            throw new CustomException("退款失败");
        }
        return JSONObject.toJSONString(response);
    }


    @Override
    @Transactional
    public boolean tixian(AliWithdrawModal modal,UserWallet userWallet) {
        //封装对象
        AlipayClient alipayClient = new DefaultAlipayClient(PayUrl.SERVER_URL, modal.getAppid(),
                modal.getPrivateKey(), PayUrl.FORMAT, PayUrl.CHARSET, modal.getPubliceKey(), PayUrl.SIGN_TYPE);
        AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();
        AlipayFundTransToaccountTransferModel model = new AlipayFundTransToaccountTransferModel();
        model.setOutBizNo(modal.getOrderId());
        model.setPayeeType("ALIPAY_USERID");
        model.setPayeeAccount(modal.getAliAccount());
        model.setAmount(modal.getMoney());
        model.setPayerShowName(modal.getPayerShowName());
        model.setRemark(modal.getRemark());
        request.setBizModel(model);
        AlipayFundTransToaccountTransferResponse response = null;
        try {
            //钱包减钱
            userWallet.setTotalPrice(userWallet.getTotalPrice().subtract(new BigDecimal(modal.getMoney())));
            userWalletService.updateUserWallet(userWallet);

            //添加提现历史记录
            insertHistoryWithdraw(modal);

            //执行提现
            response = alipayClient.execute(request);
           if (!response.isSuccess()){
               log.info("response.isSuccess:"+response.isSuccess());
               throw new CustomException("提现失败", ShowTypeEnum.用户.getValue());
           }
        } catch (AlipayApiException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }

        if (response.isSuccess() && response.getCode().equals("10000")) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean withdrawal(AliWithdrawModal modal) {
        //封装对象
        AlipayClient alipayClient = new DefaultAlipayClient(PayUrl.SERVER_URL, modal.getAppid(),
                modal.getPrivateKey(), PayUrl.FORMAT, PayUrl.CHARSET, modal.getPubliceKey(), PayUrl.SIGN_TYPE);
        AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();
        AlipayFundTransToaccountTransferModel model = new AlipayFundTransToaccountTransferModel();
        model.setOutBizNo(modal.getOrderId());
        model.setPayeeType("ALIPAY_USERID");
        model.setPayeeAccount(modal.getAliAccount());
        model.setAmount(modal.getMoney());
        model.setPayerShowName(modal.getPayerShowName());
        model.setRemark(modal.getRemark());
        request.setBizModel(model);
        AlipayFundTransToaccountTransferResponse response = null;
        try {
            //执行提现
            response = alipayClient.execute(request);
            if (!response.isSuccess()){
                log.info("response.isSuccess:"+response.isSuccess());
                throw new CustomException("提现失败", ShowTypeEnum.用户.getValue());
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        if (response.isSuccess() && response.getCode().equals("10000")) {
            return true;
        } else {
            return false;
        }
    }

    //插入历史业务记录
    private void insertHistoryWithdraw(AliWithdrawModal modal){
        //封装历史提现记录表
        HistoryWithdraw historyWithdraw = new HistoryWithdraw();
        historyWithdraw.setUserId(ApiUtils.getUserId());
        historyWithdraw.setOrdersNo(modal.getOrderId());
        historyWithdraw.setAmount(new BigDecimal(modal.getMoney()).setScale(2, BigDecimal.ROUND_HALF_UP));
        historyWithdraw.setAccount(modal.getAliAccount());
        historyWithdraw.setApp(modal.getPayerShowName());
        historyWithdraw.setPlatform("alipay");
        historyWithdraw.setUserName(modal.getPayeeRealName());
        historyWithdraw.setCreateTime(DateUtils.getNowDate());
        //插入
        historyWithdrawService.insertHistoryWithdraw(historyWithdraw);
    }

    //记录每天用户下单的次数
    private void userOrdersCount(){
        Boolean flag = redisTemplate.opsForValue().setIfAbsent("USER_ID" + ApiUtils.getUserId(), 1, DateUtils.getSeconds(), TimeUnit.SECONDS);
        if (flag !=null){
            if (!flag){
                redisTemplate.opsForValue().increment("USER_ID" + ApiUtils.getUserId());
            }
        }
        log.info(ApiUtils.getApiUser().getUsername()+":第"+redisTemplate.opsForValue().get("USER_ID" + ApiUtils.getUserId())+"单");
    }
}
